package com.ygqh.baby.controller.admin;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.foxinmy.weixin4j.util.StringUtil;
import com.ygqh.baby.ao.Message;
import com.ygqh.baby.ao.SubscribeType;
import com.ygqh.baby.po.YgSubscribeMsgDetail;
import com.ygqh.baby.po.YgUser;
import com.ygqh.baby.service.WxMpMessageService;
import com.ygqh.baby.service.YgSubscribeMsgDetailService;
import com.ygqh.baby.service.YgUserService;

@Controller
@RequestMapping("/admin/subscribemsg")
public class SubscribeMsgController extends BaseController<Object, java.lang.Long> {
	@Autowired
	private YgSubscribeMsgDetailService ygSubscribeMsgDetailService;
	@Autowired
	private YgUserService ygUserService;
	@Autowired
	private WxMpMessageService wxMpMessageService;

	@RequestMapping(value = "findCountByType")
	@ResponseBody
	public Message findCountByType(@RequestParam SubscribeType subscribeType, Boolean isSend) {

		int count = ygSubscribeMsgDetailService.findCountByType(subscribeType, null, null, isSend == null ? false : isSend);
		return Message.success(count);
	}

	@RequestMapping(value = "sendSubscribeMsg")
	@ResponseBody
	public Message sendSubscribeMsg(@RequestParam SubscribeType subscribeType, @RequestParam String title, String userName, @RequestParam String url,
			String content) {
		String openId = null;
		if (StringUtil.isNotBlank(userName)) {
			YgUser user = ygUserService.findByUserName(userName);
			if (user == null) {
				return Message.error("请输入正确的手机号。", userName);
			}
			if (StringUtil.isBlank(user.getOpenId())) {
				return Message.error("该用户尚未绑定微信", userName);
			}
			openId = user.getOpenId();
		}
		// oFtUR024P7jaNUGqn644suUaponY
		List<YgSubscribeMsgDetail> list = ygSubscribeMsgDetailService.findByType(subscribeType, openId, null, false);
		if (openId != null && CollectionUtils.isEmpty(list)) {
			return Message.error("该用户尚未订阅此消息", userName);
		}
		StringBuffer sb = new StringBuffer();
		for (YgSubscribeMsgDetail msg : list) {
			Message res = wxMpMessageService.sendSubscribeMsg(msg.getOpenId(), title, msg.getTemplateId(), url, msg.getScene(), content);
			msg.setSendTime(new Date());
			msg.setRemark(res.getContent());
			if (res.getType().equals(Message.Type.error)) {
				sb.append(res.getContent());
				msg.setIsSend(false);
			} else {
				msg.setIsSend(true);
			}
		}
		ygSubscribeMsgDetailService.updateSendStatusBatch(list);
		// if (openId == null && sb.toString().length() > 0) {
		// return Message.error(sb.toString(), null);
		// }
		return Message.success("");
	}
}
